/**
 * Created by tanbingqin on 2020/2/4.
 */
import {messages, deepFullCopy} from "share/common";
import React from 'react'
import {connect} from "react-redux";
import { message, Icon, Modal, Button, Row, Col, Input, Form, Timeline } from 'antd'
const FormItem = Form.Item;
import approveService from 'containers/approve/approve.service'
import errorMessage from 'share/errorMessage'
import Chooser from 'components/chooser'
import chooserData from 'share/chooserData'

class Designate extends React.Component{
  constructor(props) {
    super(props);
    this.state = {
      loading: false
    }
  }

  componentWillMount() {}

  componentWillReceiveProps(nextProps) {
    const { modalVisible } = this.props;
    if (!modalVisible && nextProps.modalVisible) {
      //do nothing
    }
    if (modalVisible && !nextProps.modalVisible) {
      this.props.form.resetFields();
    }
  }

  //isSuccess 是否是成功的返回
  closeDesignateModal = (isSuccess) => {
    const { onClose } = this.props;
    if (onClose) {
      onClose(isSuccess);
    }
  };

  handleDesignate = () => {
    const { entity } = this.props;
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        let params = {
          entityOID: entity.entityOID,
          entityType: entity.entityType,
          approvalDesignateNodeList: []
        };
        for (let key in values) {
          let userOIDList = [];
          values[key] && values[key].forEach(user => {
            userOIDList.push({userOID: user.userOID});
          });
          if (userOIDList.length) {
            params.approvalDesignateNodeList.push({
              ruleApprovalNodeOID: key,
              approvalDefaultUser: userOIDList
            });
          }
        }
        this.setState({loading: true});
        approveService.postDesignate(params).then(res => {
          this.setState({loading: false});
          this.closeDesignateModal(true);
        }).catch(err => {
          this.setState({loading: false});
          errorMessage(err.response);
        });
      }
    });
  };

  render() {
    const { modalVisible, nodeList, entity } = this.props;
    const { loading } = this.state;
    const { getFieldDecorator } = this.props.form;
    const formItemLayout = {
      labelCol: { span: 6, offset: 2 },
      wrapperCol: { span: 15 },
    };
    let chooserItem = deepFullCopy(chooserData['user']);
    chooserItem.url = '/api/approval/designate/node/user';
    chooserItem.searchForm[0].label = messages('common-1.key295')/*工号/姓名/部门*/;
    return (
      <div>
        <Modal
          width={700}
          className="new-form"
          title={messages('common-1.key296')/*审批流程*/}
          visible={modalVisible}
          onCancel={() => this.closeDesignateModal(false)}
          maskClosable={false}
          destroyOnClose={true}
          footer={[
            <Button key="back" onClick={() => this.closeDesignateModal(false)}>{messages('common.cancel')/*取消*/}</Button>,
            <Button key="submit" type="primary" loading={loading} onClick={() => this.handleDesignate()}>{messages('common.ok')/*确定*/}</Button>
          ]}
        >
          <div style={{maxHeight: '500px', overflowY: 'auto', paddingTop: '10px'}}>
            <Form>
              <Timeline>
                {nodeList && nodeList.length && nodeList.map(node => {
                  if (node.designateType) {
                    return (
                      <Timeline.Item>
                        <FormItem {...formItemLayout} label={node.remark}>
                          {getFieldDecorator(node.ruleApprovalNodeOID, {
                            rules: [
                              {
                                required: node.nullableRule === 2002,
                                message: messages('common.select')/*请选择*/ //请选择
                              }
                            ],
                            initialValue: node.approvalDefaultUser || undefined
                          })(
                            <Chooser
                              placeholder={messages('common.select')/*请选择*/}
                              selectorItem={chooserItem}
                              labelKey='fullName'
                              valueKey='userOID'
                              listExtraParams={{
                                ruleApprovalNodeOID: node.ruleApprovalNodeOID,
                                entityOID: entity.entityOID,
                                entityType: entity.entityType
                              }}
                              showNumber={false}
                              single={false}
                            />
                          )}
                        </FormItem>
                      </Timeline.Item>
                    )
                  } else {
                    return (
                      <Timeline.Item>
                        <Row>
                          <Col span={6} offset={2}>
                            {node.remark}
                          </Col>
                        </Row>
                      </Timeline.Item>
                    )
                  }
                })}
              </Timeline>
            </Form>
          </div>
        </Modal>
      </div>
    )
  }

}

Designate.propTypes = {
  modalVisible: React.PropTypes.bool,
  onClose: React.PropTypes.func,
  entity: React.PropTypes.object,
  nodeList: React.PropTypes.array
};

Designate.defaultProps = {
  modalVisible: false,
  onClose: () => {},
  entity: {},
  nodeList: []
};

function mapStateToProps(state) {
  return {}
}

const wrappedDesignate = Form.create()(Designate);
export default connect(mapStateToProps)(wrappedDesignate);
